import React, { useState, useEffect } from 'react'
import { View, Picker, Text } from '@tarojs/components'
import Taro, { useRouter} from '@tarojs/taro'
import { AtButton, AtList, AtListItem, AtInput, AtMessage} from 'taro-ui'
import { request } from '@/utils'
import './index.less'

const SELECTOR = [
  {
    text: '正常营业',
    value: 1,
  },
  {
    text: '停止营业',
    value: 0,
  },
]

const Edit = () => {
  const [name, setName] = useState('')
  const [openingHoursBegin, setOpeningHoursBegin] = useState('')
  const [openingHoursEnd, setOpeningHoursEnd] = useState('')
  const [phoneNo, setPhoneNo] = useState('')
  const [detailedAddress, setDetailedAddress] = useState('')
  const [selectName, setSelectName] = useState('')
  const [selectId, setSelectId] = useState('')
  const [lat, setLat] = useState('')
  const [lng, setLng] = useState('')

  const {params} = useRouter()

  const handleChange = (e, type) => {
    switch(type) {
      case 1:
        setName(e)
        break;
      case 2:
        setPhoneNo(e)
        break;
      case 3:
        setDetailedAddress(e)
        break;
    }
  }
  const onTimeChange = (e, type) => {
    const { detail: { value}} = e
    switch(type) {
      case 1:
        setOpeningHoursBegin(`${value}:00`);
        break
      case 2:
        setOpeningHoursEnd(`${value}:00`)
        break
    }
  }
  const onFillChange = (e) => {
    const { detail: { value}} = e
    setSelectName(SELECTOR[value].text)
    setSelectId(SELECTOR[value].value)
  }
  const handleSave = async () => {
    if(!name) {
      Taro.atMessage({message: '请输入油站名称', type: 'error'})
      return
    }
    if(!openingHoursBegin) {
      Taro.atMessage({message: '请选择开始营业时间', type: 'error'})
      return
    }
    if(!openingHoursEnd) {
      Taro.atMessage({message: '请选择营业关闭时间', type: 'error'})
      return
    }
    if(!detailedAddress) {
      Taro.atMessage({message: '请输入地址', type: 'error'})
      return
    }
    if(selectId != 0 && selectId != 1) {
      Taro.atMessage({message: '请选择营业状态', type: 'error'})
      return
    }
    const param = {detailedAddress, name, openingFlag: selectId, openingHoursBegin,openingHoursEnd, phoneNo, lng, lat }
    if(params.id) {
      param.id = params.id
    }
    Taro.showLoading({mask: true})
    const { error } = await request({url: 'hkshihua/user/supplier/addOrUpdate', method: 'POST', header: {'content-type': 'application/json'}, data: JSON.stringify(param)})
    if(error) return
    Taro.atMessage({ message: '保存成功', type: 'success'})
    Taro.navigateBack()
  }
  const handleAddressClick = () => {
    Taro.getSetting({
      success({authSetting}) {
        if(authSetting['scope.address']) {
          Taro.chooseLocation({
            success(res) {
              setLat(res.latitude)
              setLng(res.longitude)
            }
          })
        } else {
          Taro.authorize({
            scope: 'address',
            success() {
              Taro.chooseLocation({
                success(res) {
                  setLat(res.latitude)
                  setLng(res.longitude)
                }
              })
            }
          })
        }
      }
    })

  }
  useEffect(() => {
    setName(params.name)
    setOpeningHoursBegin(params?.openingHoursBegin)
    setOpeningHoursEnd(params?.openingHoursEnd)
    setPhoneNo(params.phoneNo)
    setDetailedAddress(params.detailedAddress)
    setSelectId(Number(params.selectedId))
    const data = SELECTOR.find((item) =>item.value == params.selectedId)
    setSelectName(data ? data.text : '请选择营业状态')
    setLat(params.lat)
    setLng(params.lng)
  }, [params.detailAddress, params.detailedAddress, params.lat, params.lng, params.name, params.openingHoursBegin, params.openingHoursEnd, params.phoneNo, params.selectId, params.selectedId])
  return (
      <View >
        <AtMessage />
        <View>

        </View>
        <View className='m-list-1'>
          <View className='m-item-1'>

            <View className='_border_1'>
              <AtInput
                cursor={-1}
                required
                name='name'
                title='油站名称'
                type='text'
                placeholder='请输入油站名称'
                value={name}
                onChange={(e) => handleChange(e, 1)}
              />
            </View>
            <View className='_border_1'>
              <Text className='tips'>*</Text>
              <Picker mode='time' onChange={(e) => onTimeChange(e, 1)}>
                <AtList>
                  <AtListItem title='营业开始时间' extraText={openingHoursBegin || '请选择'} />
                </AtList>
              </Picker>
            </View>
            <View className='_border_1'>
              <Text className='tips'>*</Text>
              <Picker mode='time' onChange={(e) => onTimeChange(e, 2)}>
                <AtList>
                  <AtListItem title='营业结束时间' extraText={openingHoursEnd || '请选择'} />
                </AtList>
              </Picker>
            </View>
            <View className='_border_1'>
              <AtInput
                cursor={-1}
                name='phoneNo'
                title='联系电话'
                type='phone'
                placeholder='请输入联系电话'
                value={phoneNo}
                onChange={(e) => handleChange(e, 2)}
              />
            </View>
            <View className='_border_1'>
              <AtInput
                cursor={-1}
                required
                name='detailedAddress'
                title='地址'
                type='text'
                placeholder='请输入地址'
                value={detailedAddress}
                onChange={(e) => handleChange(e, 3)}
              />
            </View>
            <View className='_border_1'>
              <AtListItem onClick={handleAddressClick} title='地图定位' extraText={lat && lng ? '修改': '选取'} />
            </View>
            <View className='_border_1'>
              <Picker mode='selector' range={SELECTOR} rangeKey='text' onChange={onFillChange} >
                <Text className='tips'>*</Text>
                <AtList>
                  <AtListItem
                    title='营业状态'
                    extraText={selectName}
                  />
                </AtList>
              </Picker>
            </View>
            <View style='margin-top:40px;'>
              <AtButton type='primary' onClick={handleSave} >提交</AtButton>
            </View>
          </View>

        </View>

      </View>
  )
}
export default Edit
